package com.weishaoying.mongo.config;

import com.mongodb.MongoClient;
import com.weishaoying.mongo.model.MultiMongoConfigBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

/**
 * @author WeiShaoying
 * @date 2018/5/16
 */
@Configuration
public class MongoConfig {

    //自动注入ConfigBean
    @Autowired
    private MultiMongoConfigBean mongoProperties;

    @Primary
    @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate primaryMongoTemplate() {
        return new MongoTemplate(primaryMongoDbFactory(this.mongoProperties.getPrimary()));
    }


    @Bean(name = SecondaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate secondaryMongoTemplate() {
        return new MongoTemplate(secondaryMongoDbFactory(this.mongoProperties.getSecondary()));
    }

    @Bean
    @Primary
    public MongoDbFactory primaryMongoDbFactory(MongoProperties mongoProperties) {
        return new SimpleMongoDbFactory(
                new MongoClient(mongoProperties.getHost(), mongoProperties.getPort()),
                mongoProperties.getDatabase()
        );
    }

    @Bean
    public MongoDbFactory secondaryMongoDbFactory(MongoProperties mongoProperties) {
        return new SimpleMongoDbFactory(
                new MongoClient(mongoProperties.getHost(), mongoProperties.getPort()),
                mongoProperties.getDatabase()
        );
    }
}
